<template>
  <div class="contract-management bg-gray-50 min-h-screen p-6">
    <div class="max-w-7xl mx-auto">
      <!-- 页面标题 -->
      <div class="mb-6 flex justify-between items-center">
        <h1 class="text-2xl font-bold text-gray-800">合同管理</h1>
        <button 
          @click="openCreateModal"
          class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg flex items-center"
        >
          <i class="fas fa-plus mr-2"></i>
          新建合同
        </button>
      </div>

      <!-- 搜索和筛选区域 -->
      <div class="bg-white rounded-lg shadow p-4 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">关键字</label>
            <input
              v-model="searchParams.keyword"
              type="text"
              placeholder="合同名称或描述"
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              @keyup.enter="searchContracts"
            />
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">分类</label>
            <select
              v-model="searchParams.category"
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="">全部分类</option>
              <option value="销售合同">销售合同</option>
              <option value="采购合同">采购合同</option>
              <option value="劳动合同">劳动合同</option>
              <option value="服务合同">服务合同</option>
              <option value="租赁合同">租赁合同</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">排序</label>
            <select
              v-model="searchParams.sortBy"
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="uploadTime">上传时间</option>
              <option value="name">合同名称</option>
              <option value="downloadCount">下载次数</option>
              <option value="previewCount">预览次数</option>
              <option value="favoriteCount">收藏次数</option>
            </select>
          </div>
          <div class="flex items-end space-x-2">
            <button
              @click="searchContracts"
              class="flex-1 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md"
            >
              搜索
            </button>
            <button
              @click="resetSearch"
              class="flex-1 border border-gray-300 hover:bg-gray-100 text-gray-700 px-4 py-2 rounded-md"
            >
              重置
            </button>
          </div>
        </div>
      </div>

      <!-- 合同列表 -->
      <div v-if="!loading" class="bg-white rounded-lg shadow overflow-hidden">
        <div v-if="contracts.length > 0" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 p-6">
          <div
            v-for="contract in contracts"
            :key="contract.id"
            class="border border-gray-200 rounded-lg overflow-hidden hover:shadow-lg transition-shadow"
          >
            <!-- 合同封面 -->
            <div class="h-48 bg-gray-100 relative">
              <img
                :src="contract.imgUrl || defaultImage"
                :alt="contract.name"
                class="w-full h-full object-cover"
                @error="handleImageError($event)"
              />
              <div class="absolute top-2 right-2">
                <button
                  @click="toggleFavorite(contract)"
                  class="bg-white rounded-full p-2 shadow"
                  :class="contract.isFavorite ? 'text-yellow-500' : 'text-gray-400'"
                >
                  <i :class="contract.isFavorite ? 'fas fa-star' : 'far fa-star'"></i>
                </button>
              </div>
            </div>

            <!-- 合同信息 -->
            <div class="p-4">
              <div class="flex justify-between items-start mb-2">
                <h3 class="font-semibold text-lg text-gray-800 truncate">{{ contract.name }}</h3>
                <span class="bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded">
                  {{ contract.category || '未分类' }}
                </span>
              </div>
              <p class="text-gray-600 text-sm mb-4 line-clamp-2">
                {{ contract.description || '暂无描述' }}
              </p>

              <!-- 统计信息 -->
              <div class="flex justify-between text-xs text-gray-500 mb-4">
                <span><i class="fas fa-download mr-1 text-green-500"></i> {{ contract.downloadCount || 0 }}</span>
                <span><i class="fas fa-eye mr-1 text-blue-500"></i> {{ contract.previewCount || 0 }}</span>
                <span><i class="fas fa-star mr-1 text-yellow-500"></i> {{ contract.favoriteCount || 0 }}</span>
              </div>

              <!-- 操作按钮 -->
              <div class="flex justify-between">
                <button
                  @click="previewContract(contract)"
                  class="text-blue-600 hover:text-blue-800 flex items-center text-sm"
                >
                  <i class="fas fa-eye mr-1"></i> 预览
                </button>
                <button
                  @click="downloadContract(contract)"
                  class="text-green-600 hover:text-green-800 flex items-center text-sm"
                >
                  <i class="fas fa-download mr-1"></i> 下载
                </button>
                <button
                  @click="openEditModal(contract)"
                  class="text-gray-600 hover:text-gray-800 flex items-center text-sm"
                >
                  <i class="fas fa-edit mr-1"></i> 编辑
                </button>
                <button
                  @click="deleteContract(contract)"
                  class="text-red-600 hover:text-red-800 flex items-center text-sm"
                >
                  <i class="fas fa-trash mr-1"></i> 删除
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="text-center py-12">
          <i class="fas fa-file-contract text-5xl text-gray-300 mb-4"></i>
          <p class="text-gray-500">暂无合同数据</p>
        </div>

        <!-- 分页 -->
        <div v-if="pagination.total > 0" class="border-t border-gray-200 px-6 py-4 flex items-center justify-between">
          <div class="text-sm text-gray-700">
            显示第 {{ (pagination.page - 1) * pagination.size + 1 }} 到 {{ Math.min(pagination.page * pagination.size, pagination.total) }} 条，共 {{ pagination.total }} 条
          </div>
          <div class="flex space-x-2">
            <button
              @click="changePage(pagination.page - 1)"
              :disabled="pagination.page === 1"
              class="px-3 py-1 border border-gray-300 rounded-md text-sm"
              :class="pagination.page === 1 ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'hover:bg-gray-100'"
            >
              上一页
            </button>
            <button
              v-for="page in pageNumbers"
              :key="page"
              @click="changePage(page)"
              class="px-3 py-1 border rounded-md text-sm"
              :class="page === pagination.page ? 'bg-blue-600 text-white border-blue-600' : 'border-gray-300 hover:bg-gray-100'"
            >
              {{ page }}
            </button>
            <button
              @click="changePage(pagination.page + 1)"
              :disabled="pagination.page >= pagination.totalPages"
              class="px-3 py-1 border border-gray-300 rounded-md text-sm"
              :class="pagination.page >= pagination.totalPages ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'hover:bg-gray-100'"
            >
              下一页
            </button>
          </div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-else class="bg-white rounded-lg shadow p-12 text-center">
        <i class="fas fa-spinner fa-spin text-3xl text-blue-600 mb-4"></i>
        <p class="text-gray-600">加载中...</p>
      </div>
    </div>

    <!-- 创建/编辑合同模态框 -->
    <div v-if="showModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
      <div class="bg-white rounded-lg w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div class="p-6">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-xl font-bold text-gray-800">
              {{ editingContract ? '编辑合同' : '新建合同' }}
            </h2>
            <button @click="closeModal" class="text-gray-500 hover:text-gray-700">
              <i class="fas fa-times"></i>
            </button>
          </div>

          <form @submit.prevent="saveContract">
            <div class="space-y-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">合同名称 *</label>
                <input
                  v-model="form.name"
                  type="text"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="请输入合同名称"
                />
              </div>

              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">分类 *</label>
                <select
                  v-model="form.category"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="">请选择分类</option>
                  <option value="销售合同">销售合同</option>
                  <option value="采购合同">采购合同</option>
                  <option value="劳动合同">劳动合同</option>
                  <option value="服务合同">服务合同</option>
                  <option value="租赁合同">租赁合同</option>
                </select>
              </div>

              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">描述</label>
                <textarea
                  v-model="form.description"
                  rows="3"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="请输入合同描述"
                ></textarea>
              </div>

              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">
                  合同文件 {{ editingContract ? '' : '*' }}
                </label>
                <div class="flex items-center space-x-2">
                  <input
                    ref="fileInput"
                    type="file"
                    accept=".pdf"
                    @change="handleFileChange"
                    class="hidden"
                  />
                  <input
                    type="text"
                    :value="selectedFile ? selectedFile.name : (editingContract?.fileName || '')"
                    readonly
                    class="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-gray-50"
                    placeholder="请选择PDF文件"
                  />
                  <button
                    type="button"
                    @click="$refs.fileInput.click()"
                    class="bg-gray-200 hover:bg-gray-300 px-4 py-2 rounded-md"
                  >
                    浏览
                  </button>
                </div>
                <p class="text-xs text-gray-500 mt-1">支持PDF格式，最大10MB</p>
              </div>
            </div>

            <div class="mt-6 flex justify-end space-x-3">
              <button
                type="button"
                @click="closeModal"
                class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-100"
              >
                取消
              </button>
              <button
                type="submit"
                :disabled="saving"
                class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
              >
                {{ saving ? '保存中...' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 预览模态框 -->
    <div v-if="showPreviewModal" class="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center p-4 z-50">
      <div class="bg-white rounded-lg w-full max-w-4xl max-h-[90vh] flex flex-col">
        <div class="p-4 border-b flex justify-between items-center">
          <h2 class="text-lg font-bold">{{ previewContractData?.name }} - 预览</h2>
          <div class="flex items-center space-x-3">
            <button
              @click="togglePreviewFavorite"
              class="flex items-center text-sm"
              :class="previewContractData?.isFavorite ? 'text-yellow-500' : 'text-gray-500'"
            >
              <i :class="previewContractData?.isFavorite ? 'fas fa-star' : 'far fa-star'"></i>
              <span class="ml-1">{{ previewContractData?.favoriteCount || 0 }}</span>
            </button>
            <button @click="closePreviewModal" class="text-gray-500 hover:text-gray-700">
              <i class="fas fa-times"></i>
            </button>
          </div>
        </div>
        <div class="flex-1 overflow-auto p-4 flex justify-center">
          <img
            v-if="previewImageUrl"
            :src="previewImageUrl"
            alt="合同预览"
            class="max-w-full max-h-full object-contain"
          />
          <div v-else class="flex items-center justify-center w-full h-64">
            <i class="fas fa-spinner fa-spin text-2xl text-blue-600"></i>
          </div>
        </div>
        <div class="p-4 border-t text-center">
          <button
            @click="downloadContract(previewContractData)"
            class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-md flex items-center mx-auto"
          >
            <i class="fas fa-download mr-2"></i> 下载合同
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import contractApi from '@/api/contractApi';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  name: 'ContractManagement',
  data() {
    return {
      contracts: [],
      loading: false,
      saving: false,
      showModal: false,
      showPreviewModal: false,
      editingContract: null,
      selectedFile: null,
      previewContractData: null,
      previewImageUrl: null,
      defaultImage: 'https://picsum.photos/400/300',
      
      // 搜索参数
      searchParams: {
        keyword: '',
        category: '',
        sortBy: 'uploadTime',
        direction: 'desc',
        page: 1,
        size: 9
      },
      
      // 分页信息
      pagination: {
        page: 1,
        size: 9,
        total: 0,
        totalPages: 0
      },
      
      // 表单数据
      form: {
        name: '',
        category: '',
        description: ''
      }
    };
  },
  
  computed: {
    pageNumbers() {
      const pages = [];
      const totalPages = this.pagination.totalPages;
      const currentPage = this.pagination.page;
      
      if (totalPages <= 5) {
        for (let i = 1; i <= totalPages; i++) {
          pages.push(i);
        }
      } else {
        if (currentPage <= 3) {
          pages.push(1, 2, 3, 4, 5);
        } else if (currentPage >= totalPages - 2) {
          for (let i = totalPages - 4; i <= totalPages; i++) {
            pages.push(i);
          }
        } else {
          for (let i = currentPage - 2; i <= currentPage + 2; i++) {
            pages.push(i);
          }
        }
      }
      
      return pages;
    }
  },
  
  mounted() {
    this.loadContracts();
  },
  
  methods: {
    // 加载合同列表
    async loadContracts() {
      this.loading = true;
      try {
        const params = {
          ...this.searchParams,
          page: this.searchParams.page - 1 // 后端页码从0开始
        };
        
        const response = await contractApi.getTemplates(params);
        
        // 处理响应数据
        if (response.data.content) {
          // 标准分页格式
          this.contracts = response.data.content;
          this.pagination.total = response.data.totalElements;
          this.pagination.totalPages = response.data.totalPages;
        } else if (Array.isArray(response.data)) {
          // 数组格式
          this.contracts = response.data;
          this.pagination.total = response.data.length;
          this.pagination.totalPages = 1;
        } else {
          this.contracts = [];
          this.pagination.total = 0;
          this.pagination.totalPages = 0;
        }
      } catch (error) {
        console.error('加载合同失败:', error);
        ElMessage.error('加载合同失败');
        this.contracts = [];
      } finally {
        this.loading = false;
      }
    },
    
    // 搜索合同
    searchContracts() {
      this.searchParams.page = 1;
      this.loadContracts();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchParams = {
        keyword: '',
        category: '',
        sortBy: 'uploadTime',
        direction: 'desc',
        page: 1,
        size: 9
      };
      this.loadContracts();
    },
    
    // 切换页码
    changePage(page) {
      if (page < 1 || page > this.pagination.totalPages) return;
      this.searchParams.page = page;
      this.loadContracts();
    },
    
    // 打开创建模态框
    openCreateModal() {
      this.editingContract = null;
      this.form = {
        name: '',
        category: '',
        description: ''
      };
      this.selectedFile = null;
      this.showModal = true;
    },
    
    // 打开编辑模态框
    openEditModal(contract) {
      this.editingContract = contract;
      this.form = {
        name: contract.name,
        category: contract.category,
        description: contract.description
      };
      this.selectedFile = null;
      this.showModal = true;
    },
    
    // 关闭模态框
    closeModal() {
      this.showModal = false;
      this.editingContract = null;
    },
    
    // 处理文件选择
    handleFileChange(event) {
      const file = event.target.files[0];
      if (!file) return;
      
      // 验证文件类型
      if (file.type !== 'application/pdf') {
        ElMessage.error('请选择PDF文件');
        return;
      }
      
      // 验证文件大小
      if (file.size > 10 * 1024 * 1024) {
        ElMessage.error('文件大小不能超过10MB');
        return;
      }
      
      this.selectedFile = file;
    },
    
    // 保存合同
    async saveContract() {
      if (!this.form.name || !this.form.category) {
        ElMessage.error('请填写必填字段');
        return;
      }
      
      if (!this.editingContract && !this.selectedFile) {
        ElMessage.error('请选择合同文件');
        return;
      }
      
      this.saving = true;
      try {
        let result;
        
        if (this.editingContract) {
          // 编辑合同
          if (this.selectedFile) {
            // 如果选择了新文件，则更新文件
            result = await contractApi.updateContractWithFile(
              this.editingContract.id,
              this.form,
              this.selectedFile
            );
          } else {
            // 仅更新合同信息
            result = await contractApi.updateContract(this.editingContract.id, this.form);
          }
          ElMessage.success('合同更新成功');
        } else {
          // 创建合同
          result = await contractApi.createContractWithFile(this.form, this.selectedFile);
          ElMessage.success('合同创建成功');
        }
        
        this.closeModal();
        this.loadContracts();
      } catch (error) {
        console.error('保存合同失败:', error);
        ElMessage.error(this.editingContract ? '合同更新失败' : '合同创建失败');
      } finally {
        this.saving = false;
      }
    },
    
    // 删除合同
    async deleteContract(contract) {
      try {
        await ElMessageBox.confirm(
          `确定要删除合同"${contract.name}"吗？此操作不可撤销。`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );
        
        await contractApi.deleteContract(contract.id);
        ElMessage.success('合同删除成功');
        this.loadContracts();
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除合同失败:', error);
          ElMessage.error('合同删除失败');
        }
      }
    },
    
    // 切换收藏状态
    async toggleFavorite(contract) {
      try {
        const newFavoriteState = !contract.isFavorite;
        await contractApi.toggleFavorite(contract.id, newFavoriteState);
        
        // 更新本地状态
        contract.isFavorite = newFavoriteState;
        contract.favoriteCount = newFavoriteState 
          ? (contract.favoriteCount || 0) + 1 
          : Math.max(0, (contract.favoriteCount || 0) - 1);
        
        ElMessage.success(newFavoriteState ? '收藏成功' : '已取消收藏');
      } catch (error) {
        console.error('收藏操作失败:', error);
        ElMessage.error('操作失败');
      }
    },
    
    // 预览合同
    async previewContract(contract) {
      this.previewContractData = contract;
      this.previewImageUrl = null;
      this.showPreviewModal = true;
      
      try {
        // 增加预览次数
        await contractApi.recordPreview(contract.id);
        contract.previewCount = (contract.previewCount || 0) + 1;
        
        // 获取预览图片
        const imageUrl = await contractApi.previewImage(contract.id);
        this.previewImageUrl = imageUrl;
      } catch (error) {
        console.error('预览合同失败:', error);
        ElMessage.error('预览失败');
        this.closePreviewModal();
      }
    },
    
    // 切换预览中的收藏状态
    async togglePreviewFavorite() {
      if (!this.previewContractData) return;
      
      try {
        const newFavoriteState = !this.previewContractData.isFavorite;
        await contractApi.toggleFavorite(this.previewContractData.id, newFavoriteState);
        
        // 更新预览数据
        this.previewContractData.isFavorite = newFavoriteState;
        this.previewContractData.favoriteCount = newFavoriteState 
          ? (this.previewContractData.favoriteCount || 0) + 1 
          : Math.max(0, (this.previewContractData.favoriteCount || 0) - 1);
        
        // 更新主列表中的数据
        const contractInList = this.contracts.find(c => c.id === this.previewContractData.id);
        if (contractInList) {
          contractInList.isFavorite = newFavoriteState;
          contractInList.favoriteCount = this.previewContractData.favoriteCount;
        }
        
        ElMessage.success(newFavoriteState ? '收藏成功' : '已取消收藏');
      } catch (error) {
        console.error('收藏操作失败:', error);
        ElMessage.error('操作失败');
      }
    },
    
    // 关闭预览模态框
    closePreviewModal() {
      this.showPreviewModal = false;
      this.previewContractData = null;
      this.previewImageUrl = null;
    },
    
    // 下载合同
    async downloadContract(contract) {
      try {
        // 增加下载次数
        await contractApi.recordDownload(contract.id);
        contract.downloadCount = (contract.downloadCount || 0) + 1;
        
        // 下载文件
        const response = await contractApi.downloadFile(contract.id);
        
        // 创建下载链接
        const blob = new Blob([response.data], { type: 'application/pdf' });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `${contract.name || 'contract'}.pdf`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      } catch (error) {
        console.error('下载合同失败:', error);
        ElMessage.error('下载失败');
      }
    },
    
    // 处理图片加载错误
    handleImageError(event) {
      event.target.src = this.defaultImage;
    }
  }
};
</script>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>